<template>
  <div class="page-common-layout">
    <div class="page-common-content">
      <tool-bar @search="$refs.table.refresh(true)" @reset="reset">
        <template slot="toolBtn" slot-scope="scope">
          <a-button
            class="cu-btn-primary"
            icon="carry-out"
            @click="batchApproval()"
            >批量审批</a-button
          >
        </template>
        <template slot="toolForm">
          <a-form-item :label="$ct('originatingTime', '发起时间')">
            <a-range-picker
              style="width: 280px"
              :ranges="{
                今天: [moment(), moment()],
                最近一周: [moment().add(-1, 'W'), moment()],
                最近一个月: [moment().add(-1, 'M'), moment()],
                最近三个月: [moment().add(-3, 'M'), moment()],
              }"
              :placeholder="[
                $ct('StartTime', '开始时间'),
                $ct('EndTime', '结束时间'),
              ]"
              v-model="rangePickerValue"
              @change="startTimeOnChange"
            />
          </a-form-item>
          <a-form-item
            :label="$ct('workflowBelongingTo', '所属流程')"
            class="margin-right-sm"
          >
            <a-input
              v-model="queryParam.modelName"
              :placeholder="$ct('workflowBelongingTo', '所属流程')"
            />
          </a-form-item>
        </template>
      </tool-bar>
      <DataGrid
        ref="table"
        :columns="columns"
        :url="url"
        :queryParam="queryParam"
        rowKey="taskId"
        showPagination="auto"
        :showRowSelect="false"
      >
        <span slot="renderFlowStatus" slot-scope="{ text, record, index }">
          <a-tag :color="'green'">
            等待审核
          </a-tag>
        </span>
        <span slot="serial" slot-scope="{ text, record, index }">
          {{ index + 1 }}
        </span>
        <span slot="renderAction" slot-scope="{ text, record }">
          <template>
            <a @click="handleTransaction(record)" v-action:myMission_approve>
              审批
            </a>
          </template>
        </span>
      </DataGrid>
      <task-form
        ref="taskModal"
        :visible="taskVisible"
        :loading="confirmLoading"
        :model="taskMdl"
        @cancel="taskHandleCancel(0)"
        @ok="taskHandleOk"
        @update="taskUpdate"
        @close="close"
      />
      <!-- 动态加载异步组件-->
      <!-- <component ref="taskModal" :is="plugItem" v-for="(plugItem, plugIndex) in plugs" :key='plugIndex'  :visible="taskVisible" :loading="taskConfirmLoading" :model="taskMdl" @cancel="taskHandleCancel(0)" @ok="taskHandleOk" @update="taskUpdate" @close="close"></component> -->
      <flow-chat ref="flowChatForm" />
      <!-- 批量审批 -->
      <batch-approval-modal
        ref="batchApprovalModal"
        :visible="approvalVisible"
        :loading="approvalLoading"
        @approval="reset"
        @cancel="
          () => {
            this.approvalVisible = false;
          }
        "
      />
    </div>
  </div>
</template>

<script>
import batchApprovalModal from "./modal/batchApprovalModal.vue";
import taskForm from "./modal/taskModel.vue";
import flowChat from "./flowChat.vue";
import { dataGridMixin } from "@/mixins/dataGridMixin";
import { DataGrid } from "@/components";
import moment from "moment";

export default {
  name: "TableList",
  mixins: [dataGridMixin],
  components: {
    DataGrid,
    flowChat,
    taskForm,
    batchApprovalModal,
  },
  data() {
    return {
      columns: [
        {
          title: "流程标题",
          dataIndex: "formName",
          width: 200,
          langCode: "workflowTitle",
        },
        {
          title: "所属流程",
          dataIndex: "modelName",
          langCode: "workflowBelongingTo",
        },
        {
          title: "审核环节",
          dataIndex: "taskName",
          langCode: "auditPhase",
        },

        {
          title: "发起人",
          dataIndex: "startUserId",
          align: "center",
          langCode: "sponsor",
        },
        {
          title: "发起时间",
          dataIndex: "flowStartTime",
          langCode: "originatingTime",
        },
        {
          title: "流程状态",
          dataIndex: "flowStatus",
          langCode: "ProcessStatus",
          align: "center",
          scopedSlots: {
            customRender: "renderFlowStatus",
          },
        },
        {
          title: "接收时间",
          dataIndex: "startTime",
          langCode: "receivingTime",
        },
        {
          title: "开封时间",
          dataIndex: "openingTime",
          langCode: "OpeningTime",
        },
        {
          title: "操作",
          dataIndex: "action",
          width: 120,
          align: "center",
          scopedSlots: {
            customRender: "renderAction",
          },
        },
      ],
      visible: false,
      confirmLoading: false,
      taskVisible: false,
      mdl: null,
      taskMdl: {},
      queryParam: {},
      url: {
        getPageSet: "/workflow/apiFlowableTask/getToDoTasks",
        deployModelId: "/workflow/apiFlowableModel/deployModelId",
        agree: "/workflow/apiFlowableTask/agree",
        getFlowImgByExecutionId:
          "/workflow/apiFlowableTask/getFlowImgByExecutionId",
      },
      modelType: 0,
      rangePickerValue: null,
      approvalVisible: false, // 批量审批
      approvalLoading: false,
    };
  },
  methods: {
    moment,
    // 批量审批
    batchApproval() {
      this.approvalVisible = true;
    },
    //流程办理事件
    handleTransaction(e) {
      if (null == e.openingTime || e.openingTime == "") {
        this.$post("/workflow/workflow/kaifengTreatment", {
          taskId: e.taskId,
        }).then(() => {
          this.$refs.table.refresh();
        });
      }
      const form = this.$refs.taskModal.formOpinion;
      form.resetFields(); // 清理表单数据（可不做）
      this.$post("/workflow/apiFlowableProcessInstance/clickStartProcess", {
        modelKey: e.modelKey,
        taskId: e.taskId,
        processInstanceId: e.processInstanceId,
        nodeId: e.nodeId,
        processDefinitionId: e.processDefinitionId,
      }).then((res) => {
        if (!res || res.message) {
          // this.$message.error("获取信息出现错误，请稍后再试");
          this.$message.error(res.message);
          return;
        }
        this.$refs.taskModal.mode = "1";
        this.modelType = res.lists.modelType;
        if (res.lists.modelType === "1") {
          // this.$refs.taskModal.plugs.push(() => import(`../../../../components/TopVUI/k-form-design/packages/KFormPreview/preview.vue`))
        }
        this.taskVisible = true;
        this.confirmLoading = true;
        this.taskMdl = e;
        const jsonData = res;
        this.$nextTick(() => {
          this.$refs.taskModal.loadData(e, jsonData);
        });
        this.confirmLoading = false;
      });
    },
    // 同意、驳回
    taskHandleOk(type, drawingList, values) {
      if (!values.message) return; // 点击非同意 驳回按钮时会让审批意见必填校验暂时失效，增加一个提交过滤
      let param = {
        modelKey: values.actDeModelKey,
        processDefinitionId: values.processDefinitionId,
        businessUuid: values.businessKey,
        taskNodeId: values.taskNodeId,
        outcome: values.outcome,
      };
      let {
        message,
        processInstanceId,
        taskId,
        processDefinitionId,
        actDeModelKey,
        businessKey,
        taskNodeId,
        formDesign,
        formModel,
        outcome,
        duplicateUserName,
        assignUser,
        tableName,
        ...formData
      } = values;
      formData.uuid = businessKey;
      this.$post("/form/formDatabase/formUpdate", formData).then((res) => {
        this.$post("/workflow/apiFlowableTask/agree", values).then((res) => {
          if (res.statusCode === 200) {
            this.$message.success(res.message);
            this.taskVisible = false;
            this.$refs.table.refresh();
            this.updateNextForm(param);
          } else {
            this.confirmLoading = false;
            this.$message.error(res.message);
          }
        });
      });
    },
    // 更新下一个节点表单
    updateNextForm(param) {
      this.$post(
        "/workflow/apiFlowableTask/updateNextForm",
        param
      ).then((res) => {});
    },
    // 更新
    taskUpdate(pramer, pramar) {
      this.confirmLoading = true;
      this.$post("/workflow/flowModel/updateFormDesign", pramer).then((res) => {
        if (res.statusCode === 200) {
          this.$message.success(res.message);
          this.confirmLoading = false;
        } else {
          this.$message.error(res.message);
          this.confirmLoading = false;
        }
      });
    },
    // 刷新
    close() {
      this.taskVisible = false;
      this.$refs.table.refresh();
    },
    startTimeOnChange(date, dateString) {
      this.queryParam.startTime = dateString.toString();
    },
    handleCancel() {
      this.visible = false;
    },
    // 流程图
    flowChart(record) {
      this.$post("/workflow/apiFlowableProcessInstance/clickStartProcess", {
        modelKey: record.modelKey,
        taskId: record.taskId,
        processInstanceId: record.processInstanceId,
        nodeId: record.nodeId,
        processDefinitionId: record.processDefinitionId,
      }).then((res) => {
        if (res.statusCode != 300) {
          const jsonData = res;
          // this.$refs.flowChatForm.loadData(jsonData)
          this.$refs.flowChatForm.loadData(
            jsonData,
            jsonData.lists.actDeModelId,
            jsonData.lists.actDeModelKey,
            jsonData.lists.actDeModelName,
            jsonData.lists.flowDesign,
            record
          );
        } else {
          this.$message.error(res.message);
        }
      });
    },
    // 办理提交
    handleOk(drawingList, formConf) {
      const form = this.$refs.createModal.formOpinion;
      this.confirmLoading = true;
      form.validateFields((errors, values) => {
        if (!errors) {
          this.$post(this.url.agree, {
            processInstanceId: values.processInstanceId,
            taskId: values.taskId,
            message: values.message,
            processDefinitionId: values.processDefinitionId,
          }).then((res) => {
            if (res.statusCode === 200) {
              this.$refs.table.refresh();
              this.$message.info(res.message);
            } else {
              this.confirmLoading = false;
              this.$message.error(res.message);
            }
          });
        } else {
          this.confirmLoading = false;
        }
      });
    },
    taskHandleCancel() {
      this.taskVisible = false;
    },
    reset() {
      this.queryParam = {};
      this.$refs.table.refresh(true);
      this.rangePickerValue = null;
    },
  },
};
</script>

<style lang="less"></style>
